<?php

class Codexec extends AppModel {

    var $name = 'Codexec';
    var $displayField = 'Director.name';
    var $order = "Director.name ASC";
    var $validate = array(
        'ComID' => array(
            'numeric' => array(
                'rule' => array('numeric'),
            //'message' => 'Your custom message here',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
        ),
        'Name' => array(
            'notempty' => array(
                'rule' => array('notempty'),
                'message' => 'Director name canot be left empty.',
                //'allowEmpty' => false,
                //'required' => false,
                //'last' => false, // Stop validation after this rule
                'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
        )
    );
    //The Associations below have been created with all possible keys, those that are not needed can be removed

    var $belongsTo = array(
        'Codetail' => array(
            'className' => 'Codetail',
            'foreignKey' => 'ComID',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ),
        'DirTitle' => array(
            'className' => 'DirTitle',
            'foreignKey' => 'dir_title_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ),
        'DirTitle2' => array(
            'className' => 'DirTitle',
            'foreignKey' => 'dir_title_id2',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ),
        'Director' => array(
            'className' => 'Director',
            'foreignKey' => 'director_id',
            'conditions' => '',
            'fields' => '',
            'order' => 'Director.name ASC'
        )
    );

    function import($filename) {
        $error = false;

        // open the file
        $handle = fopen($filename, "r");

        // read the 1st row as headings
        $header = fgetcsv($handle);

        // create a message container
        $return = array(
            'messages' => array(),
            'errors' => array(),
        );
        $i = 0;
        // read each data row in the file
        while (($row = fgetcsv($handle)) !== FALSE) {
            $i++;
            $data = array();

            // for each header field 
            foreach ($header as $k => $head) {
                // get the data field from Model.field
                //echo $head;exit;
                if (strpos($head, '.') !== false) {
                    $h = explode('.', $head);
                    $data[$h[0]][$h[1]] = (isset($row[$k])) ? $row[$k] : '';
                }
                // get the data field from field
                else {
                    $data['Codexec'][$head] = (isset($row[$k])) ? $row[$k] : '';
                }
            }

            $this->recursive = 1;
            $chkDir = $this->find("all", array("conditions" => array("Codexec.ComID" => $data['Codexec']['ComID'], "Codexec.Name" => $data['Codexec']['Name']), 'limit' => 1));
            if ($chkDir) {
                $data['Codexec']['id'] = $chkDir[0]['Codexec']['id'];
            }
            // see if we have an id 			
            $id = isset($data['Codexec']['id']) ? $data['Codexec']['id'] : 0;

            if (isset($data['Codexec']['App'])) {
                $delistDate = explode("/", $data['Codexec']['App']);
                $data['Codexec']['App'] = $delistDate['2'] . "-" . $delistDate['1'] . "" . -$delistDate['0'];
            }
            if (isset($data['Codexec']['Resig'])) {
                $delistDate = explode("/", $data['Codexec']['Resig']);
                $data['Codexec']['Resig'] = $delistDate['2'] . "-" . $delistDate['1'] . "" . -$delistDate['0'];
            }

            // we have an id, so we update
            if ($id) {
                // there is 2 options here, 
                // option 1:
                // load the current row, and merge it with the new data
                //$this->recursive = -1;
                //$post = $this->read(null,$id);
                //$data['Post'] = array_merge($post['Post'],$data['Post']);
                // option 2:
                // set the model id
                $this->id = $id;
            }

            // or create a new record
            else {
                $this->create();
            }

            // see what we have
            //debug($data);exit;
            //pr($data);
            // validate the row
            $this->set($data);
            $this->save($data);
            /*
              if (!$this->validates()) {
              //$this->_flash('warning');
              $return['errors'][] = __(sprintf('Codexec for Row %d failed to validate.',$i), true);
              $error=true;
              }
              //debug($this->data);exit;
              // save the row
              if (!$error && !$this->save($data)) {
              $return['errors'][] = __(sprintf('Codexec for Row %d failed to save.',$i), true);
              $error=true;
              }

              // success message!
              if (!$error) {
              $return['messages'][] = __(sprintf('Codexec for Row %d was saved.',$i), true);
              }
             */

            //if($i==10){echo"sahabj"; break;}
        }

        // close the file
        fclose($handle);

        // return the messages
        return $return;
    }

    function nameChanged($data, $comid) {
        $e = 0;
        foreach ($data as $codexec) {
            $codexecs['Codexec'][$e]['ComID'] = $comid;
            $codexecs['Codexec'][$e]['Name'] = $codexec['Name'];
            $codexecs['Codexec'][$e]['director_id'] = $codexec['director_id'];
            $codexecs['Codexec'][$e]['DIRref'] = $codexec['DIRref'];
            $codexecs['Codexec'][$e]['dir_title_id'] = $codexec['dir_title_id'];
            $codexecs['Codexec'][$e]['dir_title_id2'] = $codexec['dir_title_id2'];
            $codexecs['Codexec'][$e]['App'] = $codexec['App'];
            $codexecs['Codexec'][$e]['Resig'] = $codexec['Resig'];
            $e++;
        }
        $this->create();
        $this->saveAll($codexecs['Codexec']);
    }

}
